package px.Exam.Exam01;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest1 {
    public static void main(String[] args) {
        System.out.println("客户端启动");
        try (Socket socket = new Socket("localhost", 7788);
             //发送客户端信息
             OutputStream out = socket.getOutputStream();
             DataOutputStream dataOut = new DataOutputStream(out);
             Scanner sc = new Scanner(System.in);

             //接受服务端信息
             InputStream inputStream = socket.getInputStream();
             DataInputStream in = new DataInputStream(inputStream)) {
            while (true) {
                System.out.println("请输入要发送的消息：");
                String message = sc.nextLine();
                try {
                    //发送信息
                    dataOut.writeUTF(message);
                    System.out.println("消息发送成功！");
                    dataOut.flush();
                    if ("exit".equals(message)) {
                        System.out.println("客户端关闭");
                        break; // 结束循环
                    }

                    //接受信息
                    String s = in.readUTF();
                    System.out.print("服务端：" + socket.getInetAddress() + "端口：" + socket.getPort() + "回复了你：" + s);
                }catch (IOException e){
                    out.close();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
